//获取应用实例
const app = getApp()
var util = require('../../utils/util.js');
var apiHost = wx.getStorageSync('apiHost');
var yunId = wx.getStorageSync('yunId');
var openId = wx.getStorageSync('openId');
var userId = wx.getStorageSync('userId');

var goodOrders = new Array();
var createTime = util.formatTime(new Date()).toString();

var goodsType = "jd";
var orderType_z = "zonghe";         //综合排序
var orderType_t = "totalSalesDesc"; //销量排序
var orderType_c = "couponMoneyDesc";   //优惠券排序


Page({

  /**
   * 页面的初始数据
   */
  data: {
    indicatorDots: false,       //是否显示面板指示点（轮播图）
    autoplay: true,             //是否自动切换（轮播图）
    interval: 2500,             //自动切换时间间隔（轮播图）
    duration: 1000,             //滑动动画时长（轮播图）
    specliGoods: [],            //特卖商品集合
    jdGoodsList: [],            //京东商品集合
    JdListLength: '10',         //京东商品集合长度
    JdListStart: '0',           //京东商品集合开始
    orderTypeNum: '1',          //京东商品排序方式
    openId: '',                 //openId
    currentTab: '0',            //切换tab页数 初始化
    carts: '0',                 //购物车数量
    tabTypeList:[]             //tab切换集合

  },    
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    
    if (openId != '') {
      that.setData({
        openId: openId
      });
      that.countSpecliHeight();           //特卖内容
      that.getSpecliGoods();
      that.shopDetail();                  //商家详情
      that.getTabType();  
      that.getactivity();                 //三个广告位
    }

    // var openIdFlag = app.globalData.openId;
    // //判断是用户是否绑定了
    // if (app.globalData.openId && app.globalData.openId != '') {
    //   that.setData({
    //     openId: openIdFlag
    //   });
    //   that.countSpecliHeight();           //特卖内容
    //   that.getSpecliGoods();
    //   that.shopDetail();                  //商家详情
    //   that.getTabType();  
    // } else {
    //   // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
    //   // 所以此处加入 callback 以防止这种情况
    //   app.employIdCallback = openId => {
    //     if (openId != '') {
    //       that.setData({
    //         openId: openIdFlag
    //       });
    //       that.countSpecliHeight();           //特卖内容
    //       that.getSpecliGoods();
    //       that.shopDetail();                  //商家详情
    //       that.getTabType();                  
    //     }
    //   }
    // }

    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          windowHeight: res.windowHeight,
        });
      }
    });

    wx.showTabBar("tabBar2");

    wx.setTabBarItem({
      index: 0,
      text: '首页',
      selectedIconPath: "images/index_h.png",
      iconPath: "images/index_m.png",
      pagePath: "pages/yunShopIndex/yunShopIndex",
    })

  },

  /**
   * 获取广告位
   */
  getactivity: function () {
    var that = this;

    //期间为了显示效果可以添加一个过度的弹出框提示“加载中” 
    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });

    wx.request({
      url: apiHost + "mobile/jd/activitys",
      header: {
        "Content-Type": "application/json"
      },
      success: function (res) {
        var code = res.data.code;
        var msg = res.data.msg;
        if (code == "10000") {
          var activitysLsit = res.data.data;

          that.setData({
            activitysLsit: activitysLsit
          })

        } else {
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
        wx.hideLoading();   //隐藏加载loading
      }
    })
  },
  //跳转友惠特卖
  toYhspecial: function (e) {

    var id = e.currentTarget.dataset.toggle;

    // 加载中
    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });

    wx.navigateTo({
      url: '../yhSpecial/yhSpecial?id=' + id,
      success: function () {
        wx.hideLoading();   //隐藏加载loading
      },
    });
  },

  //获取tab页类型
  getTabType: function () {
    var that = this;

    wx.request({
      url: apiHost + "/xcx/banner/type/list",
      data: {
        yunId: yunId
      },
      header: {
        "Content-Type": "application/json"
      },
      success: function (res) {
        var code = res.data.code
        var msg = res.data.msg
        if (code="10000"){
          var typeList = res.data.data;
          that.getbanner(typeList[0].type);                   //获取轮播图
          that.setData({
            tabTypeList: typeList
          })
        }else{
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
      }
    })
  },

  //获取排序方式
  getOrderTyep: function (orderNum) {
    switch (orderNum) {
      case '1':
        return orderType_z;
        break;
      case '2':
        return orderType_t;
        break;
      case '3':
        return orderType_c;
        break;
    }
  },

  //获取轮播图
  getbanner: function (banType) {
    var that = this;

    wx.request({
      url: apiHost + "/xcx/banner/list",
      data: {
        yunId: yunId,
        openId: that.data.openId,
        'type': banType
      },
      header: {
        "Content-Type": "application/json"
      },
      success: function (res) {
        var code = res.data.code;
        var msg = res.data.msg

        if (code == "10000") {
          var banners = res.data.data;
          var imgUrls = [];
          // 轮播图集合 push
          for (var i = 0; i < banners.length; i++) {
            imgUrls.push(banners[i].image)
          }

          that.setData({
            imgUrls: imgUrls
          });
        }else{
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
      }
    })
  },
  //特卖商品
  getSpecliGoods: function () {
    var that = this;
    // 微信请求（点击分类）
    wx.request({
      url: apiHost + "xcx/goods/list/condition",
      data: {
        yunId: yunId,
        openId: that.data.openId,
        isSpecial: '1'
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        var code = res.data.code;
        var msg = res.data.msg

        if (code == "10000") {
          var specliGoodsList = res.data.data.list;
          // 特卖商品集合
          that.setData({
            specliGoods: specliGoodsList
          })
        }else{
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
      },
    });
  },

  /**
  * 获取每日必推商品
  */
  getJdjinxuan: function (start, length) {
    var that = this;

    //期间为了显示效果可以添加一个过度的弹出框提示“加载中” 
    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });

    wx.request({
      url: apiHost + "mobile/everyday/jinxuan",
      data: {
        start: start,
        length: length
      },
      header: {
        "Content-Type": "application/json"
      },
      success: function (res) {
        var code = res.data.code;
        var msg = res.data.msg;
        if (code == "10000") {
          var jdList = res.data.data.list;

          var jdGoodsListss = that.data.jdGoodsList;

          // 追加数据
          for (var i = 0; i < jdList.length; i++) {
            jdGoodsListss.push(jdList[i])
          }

          that.setData({
            jdGoodsList: jdGoodsListss
          })
        } else {
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
        wx.hideLoading();   //隐藏加载loading
      }
    })
  },
  //商家详情
  shopDetail: function () {
    var that = this;
    //商家
    wx.request({
      url: apiHost + "/xcx/store/detail",
      data: {
        yunId: yunId,
        userId: userId
      },
      header: {
        "Content-Type": "application/json"
      },
      success: function (res) {
        var code = res.data.code;
        var msg = res.data.msg

        if (code == "10000") {
          that.setData({
            shangjiadizhi: res.data.data.address,
            tel: res.data.data.phone,
            deliveryTimeType: res.data.data.deliveryTimeType,
            deliveryCost: res.data.data.deliveryCost,
            deliveryFee: res.data.data.deliveryFee,
            outCostFree: res.data.data.outCostFree,
            state: res.data.data.state,
          })
        }else{
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
      }
    })
  },

  /**
   * 获取京东商品集合
   */
  getJdGoodsList: function (start, length, orderTypea) {
    var that = this;

    //期间为了显示效果可以添加一个过度的弹出框提示“加载中” 
    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });

    wx.request({
      url: apiHost + "mobile/goods/list",
      data: {
        'type': goodsType,
        start: start,
        length: length,
        orderType: orderTypea
      },
      header: {
        "Content-Type": "application/json"
      },
      success: function (res) {
        var code = res.data.code;
        var msg = res.data.msg

        if (code == "10000") {
          var jdList = res.data.data.list;
          var jdGoodsListss = that.data.jdGoodsList;

          // 追加数据
          for (var i = 0; i < jdList.length; i++) {
            jdGoodsListss.push(jdList[i])
          }

          that.setData({
            jdGoodsList: jdGoodsListss
          })
        }else{
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
        wx.hideLoading();   //隐藏加载loading
      }
    })
  },

  //计算首页特卖商品 高度
  countSpecliHeight: function () {
    var that = this;
    /*获取指定元素高度*/
    var query2 = wx.createSelectorQuery();
    var shopHeight = "";

    query2.select('#Ztab').boundingClientRect()
    query2.exec(function (res) {
      shopHeight = res[0].height;
      wx.getSystemInfo({
        success: function (res) {
          that.setData({
            specliHeight: res.windowHeight  - shopHeight,
          });
        }
      });
    });
  },

  //获取高度
  jdGoodsHeght: function () {
    var that = this;
    /*获取指定元素高度*/
    var query1 = wx.createSelectorQuery();
    var query2 = wx.createSelectorQuery();
    var query3 = wx.createSelectorQuery();
    var banner_con = "";
    var ZtabHeight = "";
    var sortCon = "";

    // query2.select('#sortCon').boundingClientRect()
    // query2.exec(function (res) {
    //   sortCon = res[0].height;
    // });

    query3.select('#Ztab').boundingClientRect()
    query3.exec(function (res) {
      ZtabHeight = res[0].height;
      wx.getSystemInfo({
        success: function (res) {
          that.setData({
            jdGoodsHeght: res.windowHeight - ZtabHeight
          });
        }
      });
    });
  },

  //排序
  roderP: function (e) {
    var that = this;
    var orderT = e.target.dataset.toggle;
    var lengthflag = that.data.JdListLength;
    var startFlag = that.data.JdListStart;
    if (startFlag == "0") {
      startFlag = '1';
    }

    var length = parseInt(lengthflag) * parseInt(startFlag);
    that.setData({
      orderTypeNum: orderT
    })

    var orderType = that.getOrderTyep(orderT);

    that.orderGoodsList('0', length, orderType); //京东优惠商品list

  },

  //排序京东商品列表
  orderGoodsList: function (start, length, orderType) {
    var that = this;

    //期间为了显示效果可以添加一个过度的弹出框提示“加载中” 
    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });

    wx.request({
      url: apiHost + "mobile/goods/list",
      data: {
        'type': goodsType,
        start: start,
        length: length,
        orderType: orderType
      },
      header: {
        "Content-Type": "application/json"
      },
      success: function (res) {
        var code = res.data.code;
        var msg = res.data.msg

        if (code == "10000") {
          var jdList = res.data.data.list;
          that.setData({
            jdGoodsList: jdList
          })
        }else{
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
 
        wx.hideLoading();   //隐藏加载loading

      }
    })
  },

  //滚动到底部触发事件  
  searchScrollLower: function () {
    var that = this;
    var length = that.data.JdListLength;
    var startFlag = that.data.JdListStart;
    var orderT = that.data.orderTypeNum;
    var nowStart = parseInt(startFlag) + 1

    var orderType = that.getOrderTyep(orderT);

    that.setData({
      JdListStart: nowStart
    });


    // that.getJdGoodsList(nowStart, length, orderType); //京东优惠商品list

    that.getJdjinxuan(nowStart, length); //京东优惠商品list

  },
  //跳转商品详情
  goJdDetail: function (e) {
    var that = this;
    var spuId = e.currentTarget.dataset.toggle;

    // 加载中
    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });

    wx.navigateTo({
      url: '../jdDetails/jdDetails?spuId=' + spuId,
      success: function () {
        wx.hideLoading();   //隐藏加载loading
      },
    });
  },

  //获取二合一转链
  getUrl: function (spuId) {

    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });

    wx.request({
      url: apiHost + "xcx/goods/getUrl",
      data: {
        spuId: spuId,
        yunId: yunId
      },
      header: {
        "Content-Type": "application/json"
      },
      success: function (res) {
        var code = res.data.code;
        var msg = res.data.msg

        if (code == "10000") {
          var jdUrl = res.data.data;

          if (jdUrl == '') {
            wx.showToast({
              title: "红包卷已抢空",
              icon: 'none',
              duration: 2000,
              mask: true
            });
          } else {
            var strs = jdUrl.split("?");

            var url = strs[0]
            var param = strs[1]

            var paramBoj = param.split("=");
            var param2 = paramBoj[0];
            var param3 = paramBoj[1];

            //跳转京东详情
            wx.navigateTo({
              url: '../out/out?jdUrl=' + url + "&param2=" + param2 + "&param3=" + param3
            });
           
          }
        } else {
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
        wx.hideLoading();   //隐藏加载loading

      }
    })
  },
  //计算 福礼汇 
  countDFlh: function () {
    var that = this;
    /*获取指定元素高度*/
    var query2 = wx.createSelectorQuery();
    var bannerCon = "";

    query2.select('#banner_con').boundingClientRect()
    query2.exec(function (res) {
      bannerCon = res[0].height;
      wx.getSystemInfo({
        success: function (res) {
          that.setData({
            FlhHeight: res.windowHeight - bannerCon,
          });
          
        }
      });
    });
  },
  /** 
     * 滑动切换tab 
     */
  bindChange: function (e) {
    var that = this;
    var cateGorytab = 0;    //店铺商品+分类 tab
    var feekbacTab = 1;     //店铺评价 tab
    var shopSetUptab = 2;   //店铺   tab
    var currIndex = e.currentTarget.dataset.current; //获取当前tab页数


    var length = that.data.JdListLength;          //查询长度
    var Start = that.data.JdListStart;            //查询开始
    var orderNum = that.data.orderTypeNum;        //点击
    var orderType = that.getOrderTyep(orderNum);  //筛选条件

    //  重新设置tab 页数
    that.setData({ currentTab: e.detail.current });

    if (currIndex == cateGorytab) {
      that.countSpecliHeight();           //特卖内容
      that.getSpecliGoods();              //特卖商品
    } else if (currIndex == feekbacTab) {

      // that.getJdGoodsList(Start, length, orderType); //京东优惠商品list
      that.getJdjinxuan(Start, length); //京东优惠商品list
      that.jdGoodsHeght();                //京东优惠商品高度
    } else if (currIndex == shopSetUptab) {
      that.getJdGoodsList(Start, length, orderType); //京东优惠商品list
      that.countDFlh();                //京东优惠商品高度
    }
  },
  /**
   * 修改商品
   */
  updateGoods: function (e) {
    var spuId = e.target.dataset.toggle;

    wx.showToast({
      title: '加载中',
      icon: 'loading',
      mask: true
    })
    wx.navigateTo({
      url: '../goods/goods?spuId=' + spuId
    });
  },
  /** 
   * 
   * 点击tab切换 
   */
  swichNav: function (e) {
    var that = this;

    var cateGorytab = 0;    //店铺商品+分类 tab
    var feekbacTab = 1;     //店铺评价 tab
    var shopSetUptab = 2;   //店铺   tab
    var currIndex = e.currentTarget.dataset.current  //获取当前tab页数

    var banType = e.currentTarget.dataset.toggle //获取当前tab页数

    that.getbanner(banType);      //根据类型回去banner

    var length = that.data.JdListLength;          //查询长度
    var Start = that.data.JdListStart;            //查询开始
    var orderNum = that.data.orderTypeNum;        //点击
    var orderType = that.getOrderTyep(orderNum);  //筛选条件


    if (this.data.currentTab === e.target.dataset.current) {
      return false;
    } else {
      if (currIndex == cateGorytab) {
        that.countSpecliHeight();           //特卖内容
        that.getSpecliGoods();              //特卖商品
      } else if (currIndex == feekbacTab) {
        // that.getJdGoodsList(Start, length, orderType); //京东优惠商品list
        that.getJdjinxuan(Start, length); //京东优惠商品list
        that.jdGoodsHeght();                //京东优惠商品高度
      } else if (currIndex == shopSetUptab) {
        that.getJdGoodsList(Start, length, orderType); //京东优惠商品list
        that.countDFlh();                //京东优惠商品高度
      }
    }
    //  重新设置tab 页数
    that.setData({
      currentTab: e.target.dataset.current
    });
  },

  /**
 * 跳转预警商品
 */
  toShopIndex: function (e) {
    wx.showToast({
      title: '加载中',
      icon: 'loading',
      mask: true
    })
    wx.navigateTo({
      url: '../shopIndex/shopIndex'
    });
  },

  //点击商品，弹出商品详情
  goodsDetail: function (e) {
    var that = this;

    var spuId = e.currentTarget.dataset.toggle;

    that.alertDetail(spuId);//获取弹出商品详情

  },
  /**
   * 获取弹出商品详情
   */
  alertDetail: function (spuId) {
    var that = this;
    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });
    wx.request({
      url: apiHost + "/xcx/goods/alert/detail",
      data: {
        openId: openId,
        yunId: yunId,
        spuId: spuId
      },
      header: {
        "Content-Type": "application/json"
      },
      success: function (res) {

        var code = res.data.code;
        var msg = res.data.msg
        
        if (code == "10000") {
          var GodDetail = res.data.data
          that.setData({
            goodsDetails: GodDetail,
            goodsDetails_num: GodDetail.shopCartCount,
            showModal: true,
          })
        }else{
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
        wx.hideLoading();   //隐藏加载loading
      }
    })
  },
  /**
  * 隐藏模态对话框
  */
  hideModal: function () {
    this.setData({
      showModal: false
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    var that = this;
    that.onLoad();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
     * 用户点击右上角分享
     */
  onShareAppMessage: function (options) {

    var that = this;
    var goodsDetails = that.data.goodsDetails;

    console.log(goodsDetails)

    // 设置菜单中的转发按钮触发转发事件时的转发内容
    var shareObj = {
      title: goodsDetails.name,
      // desc: '最具人气的小程序开发联盟!',
      path: 'pages/Zindex/Zindex?spuId=' + goodsDetails.spuId,
      success: function (res) {
        // 转发成功之后的回调
        if (res.errMsg == 'shareAppMessage:ok') {
          console.log("转发成功之后的回调")
        }
      },
      fail: function (res) {
        // 转发失败之后的回调
        if (res.errMsg == 'shareAppMessage:fail cancel') {
          console.log("用户取消转发")
        } else if (res.errMsg == 'shareAppMessage:fail') {
          console.log("转发失败")
        }
      },
    }
    // 来自页面内的按钮的转发
    if (options.from == 'button') {
      // 此处可以修改 shareObj 中的内容
      shareObj.path = 'pages/Zindex/Zindex?spuId=' + goodsDetails.spuId;
    }
    // 返回shareObj
    return shareObj;
  }
})